package com.hxzy.config;

import com.hxzy.framework.web.filter.RepeatableFilter;
import com.hxzy.framework.web.interceptor.RepeatSubmitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * mvc配置
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

    /**
     * 自定义重复提交拦截器
     */
    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;


    /**
     * 自定义 springmvc的拦截器，解决数据防止重复提交的问题
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //对所有请求都去验证
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
    }

    /**
     * 自定义拦截器，解决HttpServeltRequest可重复读取流的问题
     * @return
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration()
    {
        //使用框架模型。构造一个原生的Filter
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //设定 Filter要实现的功能
        registration.setFilter(new RepeatableFilter());
        // 拦截所有的请求
        registration.addUrlPatterns("/*");
        //设定一个拦截器的名称，这个名字没有任何意义，给程序员看的
        registration.setName("repeatableFilter");
        //设定拦截器的执行顺序（值越小，越优先执行）
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

}
